#pragma once

#include <iostream>
#include <memory>
#include <sys/poll.h>
#include "Socket.hpp"

using namespace SocketModule;

#define MAX 4096

const int gdefaultfd = -1;

class PollServer
{
public:
    PollServer(uint16_t port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 初始化
        for (int i = 0; i < MAX; i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        // 添加listen套接字
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
    }

    void Loop()
    {
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = poll(_fds, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "timeout..." << std::endl;
                break;
            case -1:
                perror("poll");
                break;
            default:
                std::cout << "有事件就绪啦..., timeout" << std::endl;
                Dispatcher();
                TestFd();
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter()
    {
        InetAddr client;
        int newfd = _listen_socket->Accepter(&client);
        if (newfd < 0)
            return;
        std::cout << "获取新连接, client: " << client.Addr() << std::endl;
        int pos = -1;
        for (int j = 0; j < MAX; j++)
        {
            if (_fds[j].fd == gdefaultfd)
            {
                pos = j;
                break;
            }
        }
        if (pos == -1)
        {
            // 扩容--TODO
            std::cout << "服务器满了..." << std::endl;
            close(newfd);
        }
        else
        {
            _fds[pos].fd = newfd;
            _fds[pos].events |= POLLIN;
        }
    }

    void Recver(int who)
    {
        char buffer[1024];
        int n = recv(_fds[who].fd, buffer, sizeof(buffer)-1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(_fds[who].fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "读取出错, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
                continue;
            if (_fds[i].fd == _listen_socket->Fd())
            {
                if (_fds[i].revents & POLLIN)
                {
                    Accepter(); // 连接的获取
                }
            }
            else
            {
                if (_fds[i].revents & POLLIN)
                {
                    Recver(i);  // IO的处理
                }
                // else if (_fds[i].revents & POLLOUT)  TODO
            }
        }
    }

    void TestFd()
    {
        std::cout << "pollfd: ";
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
                continue;
            std::cout << _fds[i].fd << "[" << Events2String(_fds[i].events)  << "] ";
        }
    }

    std::string Events2String(short events)
    {
        std::string res;
        if (events & POLLIN) res += "POLLIN";
        if (events & POLLOUT) res += ",POLLOUT";
        return res;
    }

    ~PollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    struct pollfd _fds[MAX];
};